package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class ReadWriteLockExampleService {

    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private int sharedResource = 0;

    public void readTask() {
        rwLock.readLock().lock();
        try {
            log.info("读取共享资源: {}", sharedResource);
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void writeTask(int newValue) {
        rwLock.writeLock().lock();
        try {
            sharedResource = newValue;
            log.info("写入共享资源: {}", sharedResource);
        } finally {
            rwLock.writeLock().unlock();
        }
    }
}
